package cn.alcatraz.org.service.impl;

import cn.alcatraz.basic.exception.BusinessException;
import cn.alcatraz.basic.utils.BaiduAuditUtils;
import cn.alcatraz.basic.utils.EmailUtil;
import cn.alcatraz.basic.utils.MD5Utils;
import cn.alcatraz.basic.utils.StrUtils;
import cn.alcatraz.org.domain.Employee;
import cn.alcatraz.org.domain.Shop;
import cn.alcatraz.org.domain.ShopAuditLog;
import cn.alcatraz.org.mapper.EmployeeMapper;
import cn.alcatraz.org.mapper.ShopAuditLogMapper;
import cn.alcatraz.org.mapper.ShopMapper;
import cn.alcatraz.org.service.IShopService;
import cn.alcatraz.basic.service.impl.BaseServiceImpl;
import cn.alcatraz.org.vo.ShopEchartVo;
import cn.alcatraz.user.domain.Logininfo;
import cn.alcatraz.user.domain.User;
import cn.alcatraz.user.mapper.LogininfoMapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author alcatraz
 * @since 2022-07-01
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private LogininfoMapper logininfoMapper;

    /**
    * @Title: settlement
    * @Description: settlement
    * @Author: Alcatraz
    * @Version: 1.0
    * @Date:  2022/7/1 17:28
    * @Parameters: [shop]
    * @Return void
    */
    @Override
    public void settlement(Shop shop) {
        Employee admin = shop.getAdmin();
        //判断必要参数是否为空
        if (StringUtils.isEmpty(shop.getName())) {
            throw new BusinessException("参数不能为空，请重新输入！");
        }
        //校验店铺名称是否合规
        Boolean boo = BaiduAuditUtils.TextCensor(shop.getName());
        if (!boo) {
            throw new BusinessException("输入信息不合法");
        }
        boolean imgboo = BaiduAuditUtils.ImgCensor(shop.getLogo());
        if (!imgboo) {
            throw new BusinessException("图片信息不合法");
        }

        // 校验密码
        if (!admin.getPassword().equals(admin.getComfirmPassword())) {
            throw new BusinessException("两次密码不一致，请重新输入！");
        }

        //查询店铺是否存在
        Shop loadShopTmp = shopMapper.loadByName(shop.getName());
        if (loadShopTmp != null) {
            throw new BusinessException("店铺已注册，请更换店铺信息！");
        }
        //查询管理员已经注册过且还绑定了某个店铺
        Employee empTmp = employeeMapper.loadByUserName(admin.getUsername());
        if (empTmp != null && empTmp.getShopId() != null) {
            throw new BusinessException("该管理员已绑定店铺，请更换其他管理员！");
        }
        Employee loadAdmin = employeeMapper.loadByUserName(admin.getUsername());
        if (loadAdmin != null) {
            if (loadAdmin.getState() != 1) {
                throw new BusinessException("该管理员账户已被注销关闭,请重新输入管理员信息!");
            }
        }
        //校验管理员名称是否合规
            Boolean boo2 = BaiduAuditUtils.TextCensor(shop.getAdmin().getUsername());
            if (!boo2) {
                throw new BusinessException("输入信息不合法");
            }
            //注册管理员
            if (empTmp == null) {

                //保存admin
                employeeMapper.save(admin);
                empTmp = admin;
                String salt = StrUtils.getComplexRandomString(32);
                String saltPassword = MD5Utils.encrypByMd5(salt + admin.getPassword());
                admin.setSalt(salt);
                admin.setPassword(saltPassword);

                //将employee表字段保存到logininfo
                Logininfo logininfo = shop2Logininfo(empTmp);
                logininfoMapper.save(logininfo);
                //将logininfoID存到employee
                admin.setLogininfoId(logininfo.getId());
                employeeMapper.update(admin);
            }

            //将管理员的主键设置到店铺的外键
            shop.setAdminId(empTmp.getId());
            //保存店铺
            shopMapper.save(shop);
            //店铺的主键设置到管理员的外键
            empTmp.setShopId(shop.getId());
            //修改员工数据
            employeeMapper.update(empTmp);

    }

    private Logininfo shop2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setType(0);
        return logininfo;
    }


    /**
     * @Title: loadEcharts
     * @Description: 查询店铺报表数据
     * @Author: Alcatraz
     * @Version: 1.0
     * @Date:  2022/7/2 18:52
     * @Parameters: []
     * @Return
     */
    @Override
    public Map<String, Object> loadEcharts() {
        List<ShopEchartVo> shopEchartVos = shopMapper.loadEcharts();
        List<String>states = new ArrayList<>();
        List<Integer> counts = new ArrayList<>();
        for (ShopEchartVo shopEchartVo : shopEchartVos) {
            Integer state = shopEchartVo.getState();
            String stateStr = "";
            if(state==0){
                stateStr="待审核";
            }else if(state==-1){
                stateStr="驳回";
            }else if(state==1){
                stateStr="已审核";
            }else if(state==2){
                stateStr="待激活";
            }else if(state==-2){
                stateStr="拒绝";
            }

            states.add(stateStr);
            counts.add(shopEchartVo.getCount());
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("x", states);
        map.put("y", counts);
        return map;

    }

    @Override
    public void refuse(ShopAuditLog shopAuditLog) {
        // TODO 固定审核的操作员
        shopAuditLog.setAuditId(327);
        // 添加日志
        shopAuditLogMapper.save(shopAuditLog);
        // 获取店铺信息
        Shop shop = shopMapper.loadById(Long.valueOf(shopAuditLog.getShopId()));
        // 店铺状态修改为拒绝
        shop.setState(-2);
        shopMapper.update(shop);
        // 获取店铺管理员信息
        Employee admin = employeeMapper.loadById(shop.getAdminId());
        // 发送邮件
        String subject = "店铺入驻审核信息";
        String text = "<h1>店铺入驻审核已拒绝!</h1>";
        EmailUtil.sendMail(subject,text, admin.getEmail(),null,true);
    }
    @Override
    public void pass(ShopAuditLog shopAuditLog) {
        // TODO 固定审核的操作员
        shopAuditLog.setAuditId(327);
        // 添加日志
        shopAuditLogMapper.save(shopAuditLog);

        // 获取店铺信息
        Shop shop = shopMapper.loadById(Long.valueOf(shopAuditLog.getShopId()));
        // 店铺状态修改为已审核
        shop.setState(1);
        // 修改店铺状态
        shopMapper.update(shop);

        // 获取店铺管理员信息
        Employee admin = employeeMapper.loadById(shop.getAdminId());

        // 发送邮件
        String subject = "店铺入驻审核信息";
        String url = "http://localhost:8081/#/shop/activation?shopId=" + shop.getId();
        String text = "<h1>店铺入驻审核通过，点击下方连接激活店铺!</h1><a href=" + url + ">" + url + "</a>";
        EmailUtil.sendMail(subject,text, admin.getEmail(),null,true);
    }

    /**
    * @Title: reject
    * @Description: 驳回请求
    * @Author: Alcatraz
    * @Version: 1.0
    * @Date:  2022/7/4 16:57
    * @Parameters: [shopAuditLog]
    * @Return void
    */
    @Override
    public void reject(ShopAuditLog shopAuditLog) {
        // TODO 固定审核的操作员
        shopAuditLog.setAuditId(327);
        // 添加日志
        shopAuditLogMapper.save(shopAuditLog);
        // 获取店铺信息
        Shop shop = shopMapper.loadById(Long.valueOf(shopAuditLog.getShopId()));
        // 店铺状态修改为驳回
        shop.setState(-1);
        shopMapper.update(shop);
        // 获取店铺管理员信息
        Employee admin = employeeMapper.loadById(shop.getAdminId());
        // 发送邮件
        String subject = "店铺入驻审核信息";
        String url = "http://localhost:8081/#/shop/register2?shopId=" + shop.getId();
        String text = "<h1>店铺入驻审核被驳回!</h1><h2 style='color:red'>备注: " + shopAuditLog.getNote() + "</h2><h3>点击下方链接修改信息</h3><a href=" + url + ">" + url + "</a>";
        EmailUtil.sendMail(subject,text, admin.getEmail(),null,true);
    }
    /**
     * 店铺激活
     * @param id
     */
    @Override
    @Transactional
    public void activation(Long id) {
        Shop shop = shopMapper.loadById(id);
        if (shop.getState() == 1) {
            ShopAuditLog shopAuditLog = new ShopAuditLog();
            shopAuditLog.setShopId(Math.toIntExact(id));
            shopAuditLog.setAuditId(Math.toIntExact(shop.getAdminId()));
            shopAuditLog.setState(2);
            shop.setState(2);
            shopMapper.update(shop);
            shopAuditLogMapper.save(shopAuditLog);
        } else if (shop.getState() == 2) {
            throw new BusinessException("店铺已激活，请不要重复激活!");
        } else {
            throw new BusinessException("请重新打开链接，或重新申请审核!");
        }
    }

    @Override
    public void reRegister(Shop shop) {
        Shop loadShop = shopMapper.loadById(shop.getId());
        if (loadShop.getState() == 1) {
            throw new BusinessException("店铺审核已通过,请前往激活!");
        } else if (loadShop.getState() == -2) {
            throw new BusinessException("该店铺审核被拒绝,无法重新入驻申请!");
        } else if (loadShop.getState() == 2) {
            throw new BusinessException("该店铺已激活!");
        }
        // 关键数据字段验证
        if (shop.getName() == null) {
            throw new BusinessException("请输入店铺名称!");
        } else if (shop.getTel() == null) {
            throw new BusinessException("请输入店铺联系方式!");
        } else if (shop.getAddress() == null) {
            throw new BusinessException("请输入店铺地址!");
        }

        // 判断前端信息是否合规
        // 判断店铺名称
        if (!BaiduAuditUtils.TextCensor(shop.getName())) throw new BusinessException("店铺名称不合规,请重新输入!");
        // 判断店铺logo
        if (!BaiduAuditUtils.ImgCensor(shop.getLogo())) throw new BusinessException("店铺logo不合规,请重新上传!");

        // 判断店铺是否已入驻
        Shop loadByNameShop = shopMapper.loadByName(shop.getName());
        if (loadByNameShop != null && loadByNameShop.getId() != shop.getId()) throw new BusinessException("该店铺已入驻,请重新输入店铺信息!");

        loadShop.setName(shop.getName());
        loadShop.setState(0);
        loadShop.setAddress(shop.getAddress());
        loadShop.setTel(shop.getTel());
        loadShop.setLogo(shop.getLogo());
        shopMapper.update(loadShop);
    }

}
